<template>
  <view class="register-container">
    <view class="register-box">
      <view class="register-header">
        <text class="title">注册账号</text>
        <text class="subtitle">请填写以下信息完成注册</text>
      </view>
      
      <uni-forms :model="formState" ref="form" :rules="rules" class="register-form">
        <view class="avatar-container">
          <Avatar :src="avatarSrc" :size="120"  />
        </view>
        <uni-forms-item name="username" required>
          <uni-easyinput
            v-model="formState.username"
            placeholder="请输入用户名"
            class="input-item"
          />
        </uni-forms-item>
        
        <uni-forms-item name="password" required>
          <uni-easyinput
            v-model="formState.password"
            type="password"
            placeholder="请输入密码"
            class="input-item"
          />
        </uni-forms-item>

        <uni-forms-item name="confirmPassword" required>
          <uni-easyinput
            v-model="formState.confirmPassword"
            type="password"
            placeholder="请确认密码"
            class="input-item"
          />
        </uni-forms-item>

        <uni-forms-item name="email">
          <uni-easyinput
            v-model="formState.email"
            type="text"
            placeholder="请输入邮箱（选填）"
            class="input-item"
          />
        </uni-forms-item>

        <view class="btn-group">
          <button class="submit-btn" type="primary" @click="onFinish">注 册</button>
        </view>

        <view class="extra-links">
          <text class="link-text" @click="goToLogin">已有账号？立即登录</text>
        </view>
      </uni-forms>
    </view>
  </view>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import user from '@/api/user'
import Avatar from './component/Avatar.vue'

const avatarSrc = ref('') 

const uploadAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      avatarSrc.value = res.tempFilePaths[0]
      // 将文件对象保存到 formState
      formState.avatar = res.tempFiles[0]
    }
  })
}

const form = ref(null)
const formState = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  avatar: ''
})

const rules = {
  username: {
    rules: [{
      required: true,
      errorMessage: '请输入用户名'
    }]
  },
  password: {
    rules: [{
      required: true,
      errorMessage: '请输入密码'
    }, {
      minLength: 6,
      errorMessage: '密码长度不能少于6位'
    }]
  },
  confirmPassword: {
    rules: [{
      required: true,
      errorMessage: '请确认密码'
    }, {
      validateFunction: function(rule, value, data, callback) {
        if (value !== formState.password) {
          callback('两次输入的密码不一致')
        }
        return true
      }
    }]
  },
  email: {
    rules: [{
      format: 'email',
      errorMessage: '邮箱格式不正确'
    }]
  }
}

const onFinish = async () => {
  try {
    const valid = await form.value.validate()
    if (valid) {
      const res = await user.register({
        username: formState.username,
        password: formState.password,
        email: formState.email
      }, formState.avatar)
      
      if (res.data.code === 100200) {
        uni.showToast({ 
          title: '注册成功！', 
          icon: 'success',
          success: () => {
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/index/login' })
            }, 1500)
          }
        })
      } else {
        uni.showToast({ title: res.data.message || '注册失败', icon: 'none' })
      }
    }
  } catch (error) {
    console.error(error)
    uni.showToast({ title: '注册失败，请检查网络连接', icon: 'none' })
  }
}

const goToLogin = () => {
  uni.navigateTo({ url: '/pages/index/login' })
}

onMounted(() => {
  uni.$on('avatar-click', uploadAvatar)
})

onUnmounted(() => {
  uni.$off('avatar-click', uploadAvatar)
})
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(120deg, #f6d365 0%, #fda085 100%);
  padding: 20px;
}

.register-box {
  width: 90%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px 20px;
  box-shadow: 0 8px 32px rgba(253, 160, 133, 0.3);
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.title {
  font-size: 28px;
  color: #333;
  font-weight: bold;
  margin-bottom: 8px;
  display: block;
}

.subtitle {
  font-size: 14px;
  color: #666;
  display: block;
}

.register-form {
  margin-top: 20px;
}

.input-item {
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.btn-group {
  margin-top: 30px;
  padding: 0 15px;
}

.submit-btn {
  width: 100%;
  height: 45px;
  line-height: 45px;
  background: linear-gradient(120deg, #f6d365, #fda085);
  border-radius: 25px;
  font-size: 16px;
  color: #fff;
  border: none;
}

.submit-btn:active {
  opacity: 0.8;
}

.extra-links {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
}

.link-text {
  color: #fda085;
  padding: 0 10px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}
</style> 